package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class ChatClient extends Thread {
    private static int clientsNumber;
    private static int n = 1234;
    private static String idealHistory;
    private static int falseHistory;

    public static synchronized int getClientsNumber() {
        return clientsNumber;
    }

    public void run() {
        clientsNumber++;
        try(final Socket socket = new Socket("localhost", 7777)) {

            new Thread() {
                private DataInputStream dis = new DataInputStream(socket.getInputStream());
                private String lastMessage;
                @Override public void run() {
                    while(true) {
                        try {
                            lastMessage = dis.readUTF();
//                            if((lastMessage.startsWith("ACK ")) && (lastMessage.length() > 200)) {
//                                if(idealHistory == null) {
//                                    idealHistory = lastMessage;
//                                    System.out.println(lastMessage);
//                                } else {
//                                    if(lastMessage.equals(idealHistory)) {
//                                        System.out.println(++falseHistory);
//                                    }
//                                    System.out.println(lastMessage);
//                                }
//                            }
                        } catch (IOException e) {break;}
                    }
                }
            }.start();

            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            n++;
            dos.writeUTF("/reg " + n + " " + n);
            dos.writeUTF("/log " + n + " " + n);
            while(true) {
                dos.writeUTF("/snd URGENT");
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {}
            }

        } catch (IOException e) {}
        clientsNumber--;
    }
}